package com.eight.cloud.job.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eight.cloud.job.common.constants.ScheduleConstants;
import com.eight.cloud.job.entity.QuartzJobEntity;
import com.eight.cloud.job.model.dto.QuartzJobDto;
import com.eight.cloud.job.service.IQuartzJobService;
import com.eight.cloud.job.util.ScheduleUtils;
import com.eight.cloud.core.global.exception.CustomException;
import com.eight.cloud.core.global.result.Result;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 定时任务信息管理
 *
 * @ClassName: QuartzJobController
 * @Author: TXC
 * @Date: 2025-02-25 10:14
 **/
@RequestMapping("/job")
@RestController
public class QuartzJobController {
    @Resource
    private IQuartzJobService quartzJobService;

    @PostMapping("/add")
    public Result<QuartzJobEntity> add(@RequestBody QuartzJobDto quartzJob) {
        checkInvokeTarget(quartzJob);
        return Result.ok(quartzJobService.createQuartzJob(quartzJob));
    }

    /**
     * 查询定时任务列表
     */
    @GetMapping("/page")
    public Result<IPage<QuartzJobEntity>> list(IPage<QuartzJobEntity> page) {
        quartzJobService.getPage(page);
        return Result.ok(page);
    }


    /**
     * 修改定时任务
     */
    @PutMapping("/edit")
    public Result<Boolean> edit(@RequestBody QuartzJobDto quartzJob) {
        checkInvokeTarget(quartzJob);
        return Result.ok(quartzJobService.updateQuartzJob(quartzJob));
    }


    /**
     * 删除定时任务
     */
    @DeleteMapping("/{uuid}")
    public Result<Boolean> remove(@PathVariable String uuid) {
        return Result.ok(quartzJobService.deleteQuartzJob(uuid));
    }


    private void checkInvokeTarget(QuartzJobDto quartzJob) {
        if (StrUtil.containsIgnoreCase(quartzJob.getInvokeTarget(), ScheduleConstants.LOOKUP_RMI)) {
            throw new CustomException(500, "修改任务'" + quartzJob.getJobName() + "'失败，目标字符串不允许'rmi'调用");
        } else if (StrUtil.containsAnyIgnoreCase(quartzJob.getInvokeTarget(), new String[]{ScheduleConstants.LOOKUP_LDAP,
                ScheduleConstants.LOOKUP_LDAPS})) {
            throw new CustomException(500, "修改任务'" + quartzJob.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
        } else if (StrUtil.containsAnyIgnoreCase(quartzJob.getInvokeTarget(), new String[]{ScheduleConstants.HTTP,
                ScheduleConstants.HTTPS})) {
            throw new CustomException(500, "修改任务'" + quartzJob.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
        } else if (StrUtil.containsAnyIgnoreCase(quartzJob.getInvokeTarget(), ScheduleConstants.JOB_ERROR_STR)) {
            throw new CustomException(500, "修改任务'" + quartzJob.getJobName() + "'失败，目标字符串存在违规");
        } else if (!ScheduleUtils.whiteList(quartzJob.getInvokeTarget())) {
            throw new CustomException(500, "修改任务'" + quartzJob.getJobName() + "'失败，目标字符串不在白名单内");
        }
    }
}
